/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.hamacekj.dotaznikklient;

import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;

/**
 * Otázka s výběrem několika vzájemně se vylučujících možností.
 * @author Jan Hamáček
 */
public class RadioQuestion extends Question {
    
    public RadioQuestion(BufferedWriter out, QuestionsQueue queue){
        super(out, queue);
        question = new StringBuilder();
        options = new ArrayList<>();
    }

    @Override
    public void fromFirstLine(String firstLine) throws ProtocolException {
        try{
            String[] splitted = firstLine.split(" ");
            if(!"ASK".equals(splitted[0]) || !"RADIO".equals(splitted[1])){
                throw new ProtocolException();
            }
            id = Integer.parseInt(splitted[2]);
        }catch(IndexOutOfBoundsException | NumberFormatException e){
            throw new ProtocolException();
        }
    }

    @Override
    public void addParam(String dataLine) throws ProtocolException {
        String[] splitted = dataLine.split(" ", 2);
        switch(splitted[0]){
            case "MSG":
                if(question.length() != 0){
                    question.append("<br>");
                }
                question.append(splitted[1]);
                break;
            case "ITEM":
                options.add(new JRadioButton(splitted[1]));
                break;
        }
    }

    @Override
    public String toText() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void invokeGUIAndSendReply() {
        try{
            SwingUtilities.invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    createAndShowGUI();
                }
            });
        }catch(InterruptedException | InvocationTargetException e){}
    }

    @Override
    public void cancel() {
        if(isDisplayed()){
            frame.setVisible(false);
        }
    }

    @Override
    public boolean isDisplayed() {
        if(frame == null){
            return false;
        }
        return frame.isVisible();
    }
    
    private void createAndShowGUI(){
        frame = new JFrame("Otázka");
        Container root = frame.getContentPane();
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        JLabel label;
        if(question.length() == 0){
            label = new JLabel("<html>Odpovězte na otázku</html>");
        }else{
            label = new JLabel("<html>"+question.toString()+"</html>");
        }
        label.setVerticalAlignment(JLabel.TOP);
        ButtonGroup checkboxGroup = new ButtonGroup();
        JPanel checkboxPanel = new JPanel();
        checkboxPanel.setLayout(new BoxLayout(checkboxPanel, BoxLayout.Y_AXIS));
        int i = 0;
        final JButton ok = new JButton("Ok");
        for(JRadioButton r:options){
            i++;
            r.setActionCommand(new Integer(i).toString());
            checkboxGroup.add(r);
            checkboxPanel.add(r);
            r.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    ok.setEnabled(true);
                    selected = e.getActionCommand();
                }
            });
        }
        ok.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(selected != null){
                    frame.setVisible(false);
                    new replyThread().start();
                }
            }
        });
        ok.setEnabled(false);
        root.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 0; c.gridy = 0; c.insets = new Insets(10, 10, 10, 10);
        c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL;
        root.add(label, c);
        c.gridy = 1; c.weighty = 1;
        root.add(checkboxPanel, c);
        c.weighty = 0; c.fill = GridBagConstraints.NONE;
        c.anchor = GridBagConstraints.EAST; c.gridy = 2;
        root.add(ok, c);
        frame.pack();
        frame.setAlwaysOnTop(true);
        frame.setVisible(true);
        
    }
    
    private class replyThread extends Thread{
        @Override
        public void run(){
            unfinished.runNext();
            try{
                
                out.write("REPLY RADIO "+id+" ITEM "+selected);
                out.newLine();
                out.flush();
            }catch(IOException e){
                
            }
        }
    }
    
    private List<JRadioButton> options;
    private JFrame frame;
    private StringBuilder question;
    private String selected = null;
}
